﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VSDBM.Code.dao;
using System.Data;
using VSDBM.Code.functions;
using VSDBM.Code.dto;

public partial class Visual_CRUD_Subtype_AddSubtype : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        verificaUser();
        try
        {
            DataSet ds = OrganismDAO.select("WHERE status=1", "ORDER BY name");
            //verifica erro na querry
            if (ds.Tables.Count == 0)
            {
                Exception ex = new Exception("Table not found!");
                throw ex;
            }
            //verifica se existem organismos cadastrados.
            else if (ds.Tables[0].Rows.Count == 0)
            {
                Exception ex = new Exception("No organism found!");
                HttpContext.Current.Session["exception"] = "No organism found !";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }
            //Insere os organismos no Dropdown List(ddOrganism).
            else
            {
                ddOrganism.DataSource = ds.Tables[0];
                ddOrganism.DataTextField = "name";
                ddOrganism.DataValueField = "id";
                ddOrganism.DataBind();

            }
        }
        catch (Exception)
        {

            throw;
        }
    }
    protected void verificaUser()
    {
        VSDBM.Code.dto.User usuariologado = (VSDBM.Code.dto.User)HttpContext.Current.Session["usuariologado"];
        if (!(usuariologado.acessgroup == 1 || usuariologado.acessgroup == 2))
        {
            HttpContext.Current.Session["exception"] = "You are not authorized!";
            Response.Redirect("~/Visual/Errors/error.aspx");
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        String idOrganism = ddOrganism.SelectedValue;
        VSDBM.Code.dto.Subtype subtypeDTO = new VSDBM.Code.dto.Subtype();
        try
        {
            //verifica se algum organismo foi selecionado.
            if (idOrganism == null || idOrganism == "")
            {
                Exception ex = new Exception("No organism selected.");
                HttpContext.Current.Session["exception"] = "No organism selected !";
                Response.Redirect("../../../Visual/Errors/error.aspx");

            }
            else
            {
                //monta o subtypeDTO.
                subtypeDTO.descricao = txtDescription.Text;
                subtypeDTO.idOrganism = Convert.ToInt32(idOrganism);
                //Verifica a existência da sequência de referêcia no banco.
                DataSet verds = SequenceDAO.select("WHERE idacession='" + txtSubReferenceId.Text + "'", "");
                //inicializa o id da referencia
                int referenceId = 0;
                //Verifica a existência da sequência de referêcia no banco(passo 2).
                if (verds.Tables[0].Rows.Count > 0)
                {
                    //indica o id da referência diretamente.
                    referenceId = Convert.ToInt32(verds.Tables[0].Rows[0][0]);
                }
                else
                {

                    //tenta obter sequencia de referencia.

                    VSDBM.Code.dto.Sequence refSeq = zeseeker.runSingleeFetchPOST(txtSubReferenceId.Text, "nuccore");
                    refSeq.status = 0;
                    VSDBM.Code.dto.User usuariologado = (VSDBM.Code.dto.User)HttpContext.Current.Session["usuariologado"];
                    if (usuariologado == null)
                    {
                        Exception ex = new Exception("No autorized user found.");
                        HttpContext.Current.Session["exception"] = "No autorized user found !";
                        Response.Redirect("../../../Visual/Errors/error.aspx");
                    }
                    else
                    {
                        refSeq.iduser_register = usuariologado.id;
                    }
                    refSeq.idorganism = Convert.ToInt32(idOrganism);
                    //insere sequencia de referencia e obtem o ID dela.
                    string idacession = refSeq.idacession;
                    SequenceDAO.add(refSeq);
                    DataSet ds = SequenceDAO.select("WHERE idacession='" + idacession + "'", "");
                    referenceId = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                }
                //verifica Subtype description(unique) e insere o subtype DTO.
                SubtypeDAO.add(subtypeDTO);
                //Obtém o ID do subtype
                DataSet ds2 = SubtypeDAO.select("WHERE description='" + subtypeDTO.descricao + "'", "");
                int subtypeId = Convert.ToInt32(ds2.Tables[0].Rows[0][0]);
                //Insere ligação de subtipo com referencia
                Subtype_Reference refsub = new Subtype_Reference(0, referenceId, subtypeId);
                Subtype_ReferenceDAO.add(refsub);
               
            }
        }
        catch (Exception expton)
        {


            HttpContext.Current.Session["exception"] = expton.Message;
            Response.Redirect("../../../Visual/Errors/error.aspx");
        }

        //mostra a img Done.
        Response.Redirect("../../../Visual/CRUD/Subtype/ListSubtype.aspx");
    }
}